package cn.lijiguo.concurrency.part1.threadobjectmethods;

/**
 * WaitNotifyPrintOddEvenSync
 * 两个线程交替打印 100 以内的 奇偶数
 *  使用 synchronized 关键字 实现
 * @author lijiguo
 * @date 2020/1/6 16:40
 */
public class WaitNotifyPrintOddEvenSync {

    private static int count = 0;

    private static final Object lock = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            while (count < 100) {
                synchronized (lock) {
                    // count % 2 == 0
                    if ((count & 1) == 0) {
                        System.out.println(Thread.currentThread().getName() + ":" + count++);
                    }
                }
            }
        }, "偶数").start();

        new Thread(() -> {
            while (count < 100) {
                synchronized (lock) {
                    // count % 2 != 0
                    if ((count & 1) == 1) {
                        System.out.println(Thread.currentThread().getName() + ":" + count++);
                    }
                }
            }
        }, "奇数").start();
    }
}
